<script setup lang="ts">
import { ref, reactive, onMounted,computed,nextTick } from 'vue'
import { ElTable, ElTableColumn, ElPagination, ElInput, ElButton,ElMessage } from 'element-plus'
import type { TabsPaneContext,FormInstance, FormRules, MessageParamsWithType} from 'element-plus'
import { findPendingTaskList,getProcessTemplateList,approveProcess,revokeApprove } from "@/api/Process.js"
import { Search} from '@element-plus/icons-vue'
import { getBorrowerDetail,getBorrowerMaterialDetail,getAssetRepairDetail,getAssetReturnDetail } from "@/api/EmpProcessList.js"
import Drawer from '@/components/Drawer.vue'

//tab选项卡
const activeName = ref('first')
const handleClick = (tab: TabsPaneContext, event: Event) => {
  console.log(tab.props.label, event)
  searchParams.type = 1
  if(tab.props.label=='已处理'){
    searchParams.type = 2
  }else if(tab.props.label=='我发起'){
    searchParams.type = 3
  }
  //加载数据
  loadData()
}
//定义Process接口
interface Process {
  id: number
}
interface ProcessTemplate {
  id: number
  templateName:string
}
// 表格数据
const tableData = ref<Process[]>([])
// 审批模板列表
const templateList = ref<ProcessTemplate[]>([])

// 分页配置
const pagination = reactive({
  pageNum: 1,
  pageSize: 10,
  total: 0
})

// 搜索条件
const searchParams = reactive({
  processType: '', //审批类型
  type: 1,
  startUserName:"", //发起人
  beginTime:null,
  endTime:null,
  userId:4, //当前登录的用户id，测试数据
  status:null,
  handleBeginTime:null, //处理开始时间
  handleEndTime:null, //处理结束时间
})
// 搜索重置
const resetSearch = () => {
  searchParams.processType = ''
  searchParams.startUserName = ''
  searchParams.beginTime = null
  searchParams.endTime = null
  searchParams.status = null
  searchParams.handleBeginTime = null
  searchParams.handleEndTime = null
  loadData()
}
// 加载数据
const loadData = async () => {
  try {
    let data = {
      ...searchParams,
      ...pagination
    }
    console.log(data)
    // API调用
    findPendingTaskList(data).then(res=>{
      //console.log(res)
      if (res.data==null){
        tableData.value = null
        pagination.total = 0
      }else{
        tableData.value = res.data.list
        pagination.total = res.data.total
      }
    })
  } catch (error) {
    console.error('数据加载失败')
  }
}



//审核----
//流程新增
//新增流程部署
interface RuleForm {
  processId: number
  result: string
  userId:string
  description:string
  dialogVisible:Boolean
}
const ruleFormRef = ref<FormInstance>()
const ruleForm = reactive<RuleForm>({
  processId: 0,
  result: '',
  userId:'4', //审核id:测试数据
  description:'',
  dialogVisible:false
})
//表单验证
const rules = reactive<FormRules<RuleForm>>({
  result: [{
      required: true,
      message: '请输入流程名称',
      trigger: 'change',
    }],
  description: [
    {
      required: true,
      message: '请输入描述信息',
      trigger: 'change',
    }]
})
//表单提交
const submitForm = async (formEl: FormInstance | undefined) => {
  if (!formEl) return
  await formEl.validate((valid, fields) => {
    if (valid) {
      //ruleForm.userId = "4" //临时数据：4领导，123管理员
      approveProcess({"processId":ruleForm.processId,"result":ruleForm.result,"description":ruleForm.description})
      .then((res: { data: { message: MessageParamsWithType } })=>{
        ElMessage.success("审批完成")
        ruleForm.dialogVisible = false
        //加载数据
        loadData()
        //清空表单
        formEl.resetFields()
      })       
      console.log('submit!')
    } else {
      console.log('error submit!', fields)
    }
  })
}
//重置表单
const resetForm = (formEl: FormInstance | undefined) => {
  if (!formEl) return
  formEl.resetFields()
}
//审核
const handleApprove = (row:Process)=>{
  ruleForm.dialogVisible = true
  ruleForm.processId = row.id
  console.log(row)
}
//分页
const handleSizeChange = (val:number) => {
  console.log(`${val} items per page`)
  pagination.pageSize = val
  loadData()
}
const handleCurrentChange = (val:number) => {
  console.log(`current page: ${val}`)
  pagination.pageNum = val
  loadData()
}
const handleRevokeApprove=(row:Process) => {
  if (confirm("确认撤销该申请吗？")){
    revokeApprove(row.id).then(res=>{
      ElMessage.success("撤销成功")
      //加载数据
      loadData()
    })
  }
}
// 生命周期钩子
onMounted(() => {
  loadData()
  getProcessTemplateList().then(res=>{
    templateList.value = res.data
  })
})

//查看详情
//查看详情
const showDetail = (row)=>{
  //alert(row.processType)
  showFormData.title  = row.processType
  if (row.processType.indexOf("耗材")>=0){
    getMaterialBorrowDetail(row.businessId,1) //获取耗材出库详情
  }else if(row.processType.indexOf("资产借用")>=0){
    getAssetBorrowerDetail(row.businessId,0) //获取资产借用详情
  }else if(row.processType.indexOf("资产报修")>=0){
    getAssetRepairDetailInfo(row.businessId) //获取资产报修详情
  }else if(row.processType.indexOf("资产归还")>=0){
    getAssetReturnDetailInfo(row.businessId) //获取归还报修详情
  }


}
const showFormData = ref({
  id: '',
  createTime: "",
  username: '',
  deptName: '',
  expectedReturn: '',
  locationName: '',
  usagePurpose: '',
  operatorName:'',
  title:'',
  assets:[]
})

const formDataValues = computed( () => [
  {
    label: '出库编号:',
    value: showFormData.value.id
  },
  {
    label: '出库时间:',
    value: showFormData.value.createTime
  },
  {
    label: '借用人:',
    value: showFormData.value.username
  },
  {
    label: '借用人部门:',
    value: showFormData.value.deptName
  },
  {
    label: '经办人:',
    value: showFormData.value.operatorName
  },
  {
    label: '出库仓库:',
    value: showFormData.value.locationName
  },
  {
    label: '备注:',
    value: showFormData.value.usagePurpose
  }
])
//右侧抽屉
// 控制 Drawer 显示状态
const drawerVisible = ref(false)

// 耗材详情
const getMaterialBorrowDetail = (id,type) => {
  // 给Drawer传递数据 打开 Drawer
  // 思路：点击编号时候，调用接口获取详情接口然后根据返回的数据组合成showFormData格式的数据
  getBorrowerMaterialDetail({id,type}).then(res => {
    if (res.code === 200) {
      //console.log(res,"详情数据")
      nextTick(() => {
        showFormData.value.id = res.data.id
        showFormData.value.createTime = res.data.createTime
        showFormData.value.username = res.data.username
        showFormData.value.deptName = res.data.deptName
        showFormData.value.expectedReturn = res.data.expectedReturn
        showFormData.value.locationName = res.data.locationName
        showFormData.value.usagePurpose = res.data.usagePurpose
        showFormData.value.operatorName = res.data.operatorName
        tableDataByDetail.value = res.data.materialBorrowVoList
        //console.log(formDataValues.value,6666)
      })
    }
  })
  drawerVisible.value = true
}

// tableData
const tableColumns = ref([
  { prop: 'code', label: '耗材编码' },
  { prop: 'name', label: '耗材名称' },
  { prop: 'categoryName', label: '耗材分类' },
  { prop: 'specification', label: '规格' },
  { prop: 'unit', label: '单位' },
  { prop: 'warehouseName', label: '出库仓库' },
  { prop: 'quantity', label: '当前库存' },
  { prop: 'materialNum', label: '出库数量' },
  { prop: 'materialDesc', label: '出库备注' },
])

const tableDataByDetail = ref([])

// 关闭 Drawer 的方法
const closeDrawer = () => {
  drawerVisible.value = false
}

// 资产借用

const drawerVisibleByAssetBorrow = ref(false)
const showFormDataByAssetBorrow = ref({
  id: '',
  createTime: "",
  username: '',
  deptName: '',
  expectedReturn: '',
  locationName: '',
  usagePurpose: '',
  assets:[]
})
const getAssetBorrowerDetail = (id,type) => {
  // 给Drawer传递数据 打开 Drawer
  // 思路：点击编号时候，调用接口获取详情接口然后根据返回的数据组合成showFormData格式的数据
  getBorrowerDetail({id,type}).then(resp => {
    if (resp.code === 200) {
      //console.log(resp,"详情数据")
      nextTick(() => {
        showFormDataByAssetBorrow.value.id = resp.data.id
        showFormDataByAssetBorrow.value.createTime = resp.data.createTime
        showFormDataByAssetBorrow.value.username = resp.data.username
        showFormDataByAssetBorrow.value.deptName = resp.data.deptName
        showFormDataByAssetBorrow.value.expectedReturn = resp.data.expectedReturn
        showFormDataByAssetBorrow.value.locationName = resp.data.locationName
        showFormDataByAssetBorrow.value.usagePurpose = resp.data.usagePurpose
        tableDataByAssetBorrow.value = resp.data.assets
        //console.log(formDataValues.value,7777)
      })
    }
  })
  drawerVisibleByAssetBorrow.value = true
}


const formDataValuesByAssetBorrow = computed( () => [
  {
    label: '借用人部门:',
    value: showFormDataByAssetBorrow.value.deptName
  },
  {
    label: '借用人:',
    value: showFormDataByAssetBorrow.value.username
  },
  {
    label: '借用后位置:',
    value: showFormDataByAssetBorrow.value.locationName
  },
  {
    label: '备注:',
    value: showFormDataByAssetBorrow.value.usagePurpose
  },
  {
    label: '预计归还时间:',
    value: showFormDataByAssetBorrow.value.expectedReturn
  },
  {
    label: '创建时间:',
    value: showFormDataByAssetBorrow.value.createTime
  }
])



// tableData
const tableColumnsByAssetBorrow = ref([
  {prop: 'assetCode', label: '资产编码'},
  { prop: 'name', label: '资产名称' },
  { prop: 'categoryName', label: '资产分类' },
  { prop: 'model', label: '型号规格' },
  //{ prop: 'status', label: '状态' },
  // { prop: 'serialNumber', label: '序列号' },
  { prop: 'locationName', label: '位置' }
])
const tableDataByAssetBorrow = ref([])
// 关闭 Drawer 的方法
const closeDrawerByAssetBorrow = () => {
  drawerVisibleByAssetBorrow.value = false
}

// 资产报修详情
const drawerVisibleByAssetRepair = ref(false)
const showFormDataByAssetRepair = ref({
  id: '',
  createTime: "",
  username: '',
  deptName: '',
  locationName: '',
  faultDesc: '',
  assets:[]
})
const getAssetRepairDetailInfo = (id) => {
  getAssetRepairDetail(id).then(resp => {
    if (resp.code === 200) {
      console.log(resp,"详情数据")
      nextTick(() => {
        showFormDataByAssetRepair.value.id = resp.data.id
        showFormDataByAssetRepair.value.createTime = resp.data.createTime
        showFormDataByAssetRepair.value.username = resp.data.username
        showFormDataByAssetRepair.value.deptName = resp.data.deptName
        showFormDataByAssetRepair.value.locationName = resp.data.locationName
        showFormDataByAssetRepair.value.faultDesc = resp.data.faultDesc
        tableDataByAssetBorrow.value = resp.data.assets
      })
    }
  })
  drawerVisibleByAssetRepair.value = true
}
const formDataValuesByAssetRepair = computed( () => [
  {
    label: '维修编号:',
    value: showFormDataByAssetRepair.value.id
  },
  {
    label: '创建时间:',
    value: showFormDataByAssetRepair.value.createTime
  },
  {
    label: '报修人:',
    value: showFormDataByAssetRepair.value.username
  },
  {
    label: '报修人部门:',
    value: showFormDataByAssetRepair.value.deptName
  },
  {
    label: '送检地点:',
    value: showFormDataByAssetRepair.value.locationName
  },
  {
    label: '备注:',
    value: showFormDataByAssetRepair.value.faultDesc
  }
])
// 关闭 Drawer 的方法
const closeDrawerByAssetRepair = () => {
  drawerVisibleByAssetRepair.value = false
}

// 资产归还详情
const drawerVisibleByAssetReturn = ref(false)
const showFormDataByAssetReturn = ref({
  id: '',
  createTime: '',
  // username: '',
  deptName: '',
  locationName: '',
  usagePurpose: '',
  assets:[]
})
const getAssetReturnDetailInfo = (id) => {
  getAssetReturnDetail(id).then(resp => {
    if (resp.code === 200) {
      console.log(resp,"详情数据")
      nextTick(() => {
        showFormDataByAssetReturn.value.id = resp.data.id
        showFormDataByAssetReturn.value.createTime = resp.data.createTime
        showFormDataByAssetReturn.value.username = resp.data.username
        showFormDataByAssetReturn.value.deptName = resp.data.deptName
        showFormDataByAssetReturn.value.expectedReturn = resp.data.expectedReturn
        showFormDataByAssetReturn.value.locationName = resp.data.locationName
        showFormDataByAssetReturn.value.usagePurpose = resp.data.usagePurpose
        tableDataByAssetBorrow.value = resp.data.assets
      })
    }
  })
  drawerVisibleByAssetReturn.value = true
}
const formDataValuesByAssetReturn = computed( () => [
  {
    label:'归还编号',
    value: showFormDataByAssetReturn.value.id
  },
  {
    label: '归还时间',
    value: showFormDataByAssetReturn.value.createTime
  },
  // {
  //   label: '归还人员',
  //   value: showFormData.value.username
  // },
  {
    label: '归还后使用部门',
    value: showFormDataByAssetReturn.value.deptName
  },
  {
    label: '归还后位置',
    value: showFormDataByAssetReturn.value.locationName
  },
  {
    label: '备注',
    value: showFormDataByAssetReturn.value.usagePurpose
  }
])
// 关闭 Drawer 的方法
const closeDrawerByAssetReturn = () => {
  drawerVisibleByAssetReturn.value = false
}


</script>

<template>
  <div class="">
    <el-tabs v-model="activeName" class="demo-tabs" @tab-click="handleClick">
      <el-tab-pane label="待处理" name="first"></el-tab-pane>
      <el-tab-pane label="已处理" name="second"></el-tab-pane>
      <el-tab-pane label="我发起" name="third"></el-tab-pane>
    </el-tabs>

    <el-form :inline="true" :model="queryForm">
      <el-form-item>
        <el-select v-model="searchParams.processType" placeholder="请选择审批类型"
          style="width: 230px; margin-right: 10px" clearable>
          <el-option v-for="template in templateList"
              :label="template.templateName"
              :value="template.id"
              :key="template.id"
              >
          </el-option>
          <!-- 使用图标组件 -->
          <template #prefix>
            <el-icon>
              <Search />
            </el-icon>
          </template>
        </el-select>
        <el-input
            v-model="searchParams.startUserName"
            placeholder="请输入发起人"
            style="width: 230px;margin-right: 10px"
            clearable
            v-if=" searchParams.type != 3"
        >
          <!-- 使用图标组件 -->
          <template #prefix>
            <el-icon>
              <Search />
            </el-icon>
          </template>
        </el-input>

<!--      </el-form-item>
      <el-form-item label="">-->
        <el-select v-model="searchParams.status" placeholder="请选择审批状态"
                   style="width: 230px;" clearable v-if=" searchParams.type != 1">
          <el-option label="审批中" value="1"/>
          <el-option label="已通过" value="2"/>
          <el-option label="已撤回" value="3"/>
          <el-option label="已驳回" value="-1"/>
          <!-- 使用图标组件 -->
          <template #prefix>
            <el-icon>
              <Search />
            </el-icon>
          </template>
        </el-select>
<!--      </el-form-item>
      <el-form-item label="">-->
        <el-date-picker
            v-model="searchParams.beginTime"
            type="date"
            placeholder="请选择申请开始日期"
            style="width: 230px;margin-left: 10px"
            clearable
          />
        -
        <el-date-picker
            v-model="searchParams.endTime"
            type="date"
            placeholder="请选择申请结束日期"
            style="width: 230px;"
            clearable
          />
      </el-form-item>

<!--      <el-form-item label="处理日期" v-if=" searchParams.type == 2">
        <el-date-picker
          v-model="searchParams.handleBeginTime"
          type="date"
          placeholder="请选择开始日期"
          style="width: 230px;"
          clearable
        />
        -
      <el-date-picker
          v-model="searchParams.handleEndTime"
          type="date"
          placeholder="请选择结束日期"
          style="width: 230px;"
          clearable
        />
      </el-form-item>-->
      <el-form-item>
        <el-button type="primary" @click="loadData">
          <el-icon>
            <el-icon-search/>
          </el-icon>
          搜索
        </el-button>
        <el-button @click="resetSearch" type="primary" plain>
          <el-icon>
            <el-icon-refresh/>
          </el-icon>
          重置
        </el-button>
      </el-form-item>
    </el-form>

    <el-table :data="tableData" style="width: 100%;">
      <el-table-column prop="startDeptName" label="发起部门" v-if=" searchParams.type != 3"  width="150"/>
      <el-table-column prop="startUserName" label="发起人" v-if=" searchParams.type != 3"  width="100"/>
      <el-table-column label="处理状态" v-if="searchParams.type != 1" align="center" width="100">
        <template #default="scope">
          <el-tag class="mx-1" type="primary" v-if="scope.row.status==1">审批中</el-tag>
          <el-tag class="mx-1" type="success" v-if="scope.row.status==2">已通过</el-tag>
          <el-tag class="mx-1" type="warning" v-if="scope.row.status==3">已撤回</el-tag>
          <el-tag class="mx-1" type="danger" v-if="scope.row.status==-1">已驳回</el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="code" label="单据编号" align="center"/>
      <el-table-column prop="title" label="标题" align="center"/>
      <el-table-column prop="processType" label="类型" align="center"/>
      <el-table-column prop="description" label="当前节点" v-if=" searchParams.type == 3" align="center"/>
      <el-table-column prop="createTime" label="发起时间" align="center" width="120"/>
      <el-table-column prop="handleTime" label="处理时间" v-if=" searchParams.type == 2" align="center" width="120"/>
      <el-table-column label="操作" width="200"  align="center">
        <template #default="scope">
          <el-button link type="primary" @click="handleApprove(scope.row)" v-if=" searchParams.type == 1" >
            <el-icon><el-icon-edit /></el-icon>审核
          </el-button>
          <el-button link type="primary" @click="handleRevokeApprove(scope.row)"
                     v-if=" searchParams.type==3 && scope.row.status==1">
            <el-icon><el-icon-edit /></el-icon>撤销
          </el-button>
          <el-button link type="primary" @click="showDetail(scope.row)"  >
            <el-icon><el-icon-edit /></el-icon>查看详情
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <el-pagination
      v-model:current-page="pagination.pageNum"
      v-model:page-size="pagination.pageSize"
      :total="pagination.total"
      layout="slot, prev, pager, next"
      style="margin-top: 20px"
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange">
      <el-text key="1">总条数：{{ pagination.total }}</el-text>
    </el-pagination>

    <!--审核对话框-->
    <el-dialog
      v-model="ruleForm.dialogVisible"
      title="申请审批"
      width="500" >
      <el-form
        ref="ruleFormRef"
        style="max-width: 600px"
        :model="ruleForm"
        :rules="rules"
        label-width="auto"
      >        
        <el-form-item label="审批状态" prop="result">
          <el-select v-model="ruleForm.result" placeholder="请选择审批状态" clearable>
            <el-option label="通过" value="1" />
            <el-option label="驳回" value="0" />
          </el-select>
        </el-form-item>        
        <el-form-item label="审批意见" prop="description">
          <el-input v-model="ruleForm.description" type="textarea" clearable/>
        </el-form-item>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm(ruleFormRef)">确定</el-button>
          <el-button @click="resetForm(ruleFormRef)">重置</el-button>
        </div>
      </el-form>
    </el-dialog>


    <!--------------- 耗材出库详情抽屉 ----------------->
    <Drawer v-model:visible="drawerVisible" :formData="showFormData" :title="'耗材出库详情'"
            :formDataValues="formDataValues" :tableColumns="tableColumns" :tableData="tableDataByDetail" @close="closeDrawer" />
    <!--------------- 资产借用详情抽屉 ----------------->
    <Drawer v-model:visible="drawerVisibleByAssetBorrow" :formData="showFormDataByAssetBorrow" :title="'资产借用详情'"
            :formDataValues="formDataValuesByAssetBorrow" :tableColumns="tableColumnsByAssetBorrow"
            :tableData="tableDataByAssetBorrow" @close="closeDrawerByAssetBorrow" />

    <!--------------- 资产报修详情抽屉 ----------------->
    <Drawer v-model:visible="drawerVisibleByAssetRepair" :formData="showFormDataByAssetRepair" :title="'资产报修详情'"
            :formDataValues="formDataValuesByAssetRepair" :tableColumns="tableColumnsByAssetBorrow"
            :tableData="tableDataByAssetBorrow" @close="closeDrawerByAssetRepair" />
    <!--------------- 资产归还详情抽屉 ----------------->
    <Drawer v-model:visible="drawerVisibleByAssetReturn" :formData="showFormDataByAssetReturn" :title="'资产归还详情'"
            :formDataValues="formDataValuesByAssetReturn" :tableColumns="tableColumnsByAssetBorrow"
            :tableData="tableDataByAssetBorrow" @close="closeDrawerByAssetReturn" />

  </div>
</template>

<style scoped>
.page-container {
  padding: 20px;
  background: #fff;
  border-radius: 4px;
}

.search-bar {
  display: flex;
  align-items: center;
  margin-bottom: 20px;
}
.dialog-footer {
  display: flex;
  justify-content: flex-end;
  margin-top: 20px;
}
.demo-tabs > .el-tabs__content {
  padding: 32px;
  color: #6b778c;
  font-size: 32px;
  font-weight: 600;
}
.el-pagination {
  display: flex;
  justify-content: flex-end;
  margin-top: 20px;
}
</style>